<template>
  <div class="content">
    <cus-search class="mb_20">
      <cus-search-item>
        <Form class="flex" ref="formValidate" :model="form" :label-width="120">
          <FormItem class="mr_48 mb_20" label="采购周期:">
            <div class="flex">
              <el-date-picker
                type="week"
                format="yyyy 第 WW 周"
                v-model="form.dateTime[0]"
                placeholder="选择周"
                :picker-options="{'firstDayOfWeek': 1}"
                @change="dateWeekChange"
                transfer
                :clearable="false"
              >
              </el-date-picker>
            </div>
          </FormItem>
          <FormItem class="mr_48 mb_20" label="审核状态:" prop="organAuditState">
            <Select
              v-model="form.organAuditState"
              placeholder="全部"
              clearable
              style="width: 200px"
            >
              <Option :value="'all'">全部</Option>
              <Option :value="1">待审核</Option>
              <Option :value="2">已审核通过（机关）</Option>
              <Option :value="3">已驳回</Option>
              <!-- <Option :value="4">已撤销</Option> -->
              <Option :value="5">已自动审核</Option>
            </Select>
          </FormItem>
          <FormItem class="mr_48 mb_20" label="伙食单位:" prop="unitCode">
            <Select
              v-model="form.unitCode"
              placeholder="全部"
              clearable
              style="width: 200px"
            >
              <Option
                :value="item.unitCode"
                v-for="(item, index) in subCanteenList"
                :key="index"
                >{{ item.unitName }}</Option
              >
            </Select>
          </FormItem>
          <Button
            class="mr_24 mb_20"
            type="primary"
            @click="
              pages.page = 1;
              onInit();
            "
            >查询</Button
          >
          <Button class="mr_24 mb_20" type="default" @click="reset()">重置</Button>
        </Form>
      </cus-search-item>
    </cus-search>
    <div class="content-bottom">
      <div class="btnBox fw">
        <div class="fz" v-if="!loading">
          本周已提报审核单位 {{ submitNum || 0 }} 个 未提报单位<a
            @click="onNotSubmitModel()"
          >
            {{ notSubmitNum }}
          </a>
          个
        </div>
      </div>
      <cusTable
        border
        ref="selection"
        :loading="loading"
        :columns="columns"
        :data="data"
        :bottomClass="['cus-page']"
      >
        <template slot-scope="{ row }" slot="operation">
          <div class="flex">
            <Button
              class="mr_10"
              type="primary"
              size="small"
              :style="{ color: '#ffffff', padding: '0 8px' }"
              @click="onShow(row)"
            >
              详情
            </Button>
            <Button
              type="primary"
              size="small"
              v-permission="20"
              v-if="[2,1].indexOf(row.organAuditState) != -1"
              :style="{ color: '#ffffff', padding: '0 8px' }"
              @click="onExamineVerifyChange(row)"
            >
              {{ row.organAuditState == 2 ? "撤销审核" : "审核" }}
            </Button>
          </div>
        </template>
      </cusTable>
      <div class="cus_page">
        <cus-page
          :data="pages"
          class="mt_20"
          @pageChange="postPurchasingPlansApi()"
        ></cus-page>
      </div>
    </div>
    <!--详情-->
    <detailedInformation ref="detailedInformation"></detailedInformation>
    <!--审核-->
    <examineVerify ref="examineVerify"></examineVerify>
    <!--未提交列表-->
    <notSubmitModel ref="notSubmitModel"></notSubmitModel>
  </div>
</template>
  
<script>
import { postPurchasingPlans } from "@/api/organ/manager";
import { getSubCanteenList } from "@/api/organ/organization";
import examineVerify from "./components/examineVerify";
import detailedInformation from "./components/detailedInformation";
import notSubmitModel from "./components/notSubmitModel";

import moment from "moment";
// require 方式
require("moment/locale/zh-cn");
moment.locale("zh-cn", {
  week: {
    dow: 1,
  },
});
import "moment/locale/zh-cn";

moment.locale("zh-cn");
export default {
  components: { examineVerify, detailedInformation, notSubmitModel },
  data() {
    return {
      loading: false,
      ruleValidate: {},
      form: {
        dateTime: [
          new Date(
            new Date().setHours(0, 0, 0) -
              (new Date().getDay() - 8) * 24 * 60 * 60 * 1000
          ),
          new Date(
            new Date().setHours(0, 0, 0) +
              (14 - new Date().getDay()) * 24 * 60 * 60 * 1000
          ),
        ], // 采购时间
        organAuditState: "all", // 机关审核状态1-待审核、2-已审核通过、3-已驳回、4-无需审核
        unitCode: "all", // 伙食单位编码
      },
      notSubmitNum: 0, // 未提交数量
      submitNum: null, // 已提交数量
      subCanteenList: [{ unitCode: "all", unitName: "全部" }], // 伙食单位列表
      data: [],
      columns: [
        // {
        //   type: "selection",
        //   width: 60,
        //   align: "center",
        // },
        {
          title: "序号",
          width: 70,
          type: "index",
          align: "center",
        },
        {
          title: "伙食单位",
          key: "unitName",
          width: 245,
          resizable: true,
          align: "center",
        },
        {
          title: "采购周期",
          key: "purchasingDate",
          width: 245,
          resizable: true,
          align: "center",
        },
        {
          title: "提交时间",
          key: "lastSubmitTime",
          width: 245,
          sortable: true,
          resizable: true,
          align: "center",
        },
        {
          title: "审核状态",
          key: "organAuditStateName",
          width: 245,
          resizable: true,
          align: "center",
        },
        {
          title: "备注",
          key: "remark",
          // width: 260,
          resizable: true,
          align: "center",
        },
        {
          title: "操作",
          width: 245,
          fixed: "right",
          slot: "operation",
          align: "center",
        },
      ],
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0,
      },
      tableHeight: 0,
    };
  },
  created() {
  },
  mounted() {
    this.getSubCanteenListApi();
    this.onInit();
    setTimeout(() => {
      this.tableHeight = window.innerHeight - 373; // 表格自适应高度
    }, 100);
    window.addEventListener("resize", this.tableHeightChange, true);
    this.onShowDetailed();
  },
  activated() {
    this.onShowDetailed();
  },
  destroyed() {
    window.removeEventListener("resize", this.tableHeightChange, true);
  },
  methods: {
    tableHeightChange() {
      this.tableHeight = 0;
      setTimeout(() => {
        this.tableHeight = window.innerHeight - 355; // 表格自适应高度
        console.log(this.tableHeight);
      }, 100);
    },
    // 初始化
    onInit() {
      this.postPurchasingPlansApi();
    },
    // 重置搜索
    reset() {
      this.$refs["formValidate"].resetFields();
      (this.form.dateTime = [
        new Date(
          new Date().setHours(0, 0, 0) -
            (new Date().getDay() - 8) * 24 * 60 * 60 * 1000
        ),
        new Date(
          new Date().setHours(0, 0, 0) +
            (14 - new Date().getDay()) * 24 * 60 * 60 * 1000
        ),
      ]),
        (this.pages.page = 1);
      this.onInit();
    },
    dateWeekChange(time) {
      this.form.dateTime[0] = this.getCurrentWeek(time)[0];
      this.form.dateTime[1] = this.getCurrentWeek(time)[6];
    },
    // 添加
    onAdd() {},
    // 删除
    onDelete(row) {
      localDishDelete({
        dishCode: row.dishCode,
      }).then((res) => {
        if (res.retCode === 2000) {
          this.$Message.success("删除成功.");
          this.onInit();
        }
      });
    },
    onNotSubmitModel() {
      this.$refs["notSubmitModel"].show(this.form);
    },
    // 详情
    onShow(row) {
      this.$refs["detailedInformation"].periodId = row.id;
      this.$refs["detailedInformation"].form.updateTime = this.form.dateTime;
      this.$refs["detailedInformation"].show();
    },
    // 审核
    onExamineVerifyChange(nVew) {
      this.$refs["examineVerify"].show(nVew);
    },
    // 采购计划查看列表--------------------接口
    postPurchasingPlansApi() {
      this.loading = true;
      return new Promise((resolve) => {
        let params = {
          startDate: this.form.dateTime[0]
            ? new Date(this.form.dateTime[0]).Format("yyyy-MM-dd")
            : null,
          stopDate: this.form.dateTime[1]
            ? new Date(this.form.dateTime[1]).Format("yyyy-MM-dd")
            : null,
          organAuditState:
            this.form.organAuditState == "all" ? "" : this.form.organAuditState,
          unitCode: this.form.unitCode == "all" ? "" : this.form.unitCode,
          currentPage: this.pages.page,
          pageSize: this.pages.pageSize,
        };
        postPurchasingPlans(params).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            this.submitNum = this.$cu.deepClone(res.data.submitNum);
            this.notSubmitNum = this.$cu.deepClone(res.data.notSubmitNum);
            this.data = res.data.purchasingPlanVos.list;
            this.pages.pageTotal = res.data.purchasingPlanVos.total;
            resolve();
          }
        });
      });
    },
    // 获取所有的伙食单位-----------------------接口
    getSubCanteenListApi() {
      this.loading = true;
      return new Promise((resolve) => {
        getSubCanteenList({
          currentPage: 1,
          pageSize: 1000,
        }).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            this.subCanteenList = this.subCanteenList.concat(res.data.list);
            resolve();
          }
        });
      });
    },
    // 获取本周日期组件处理
    getCurrentWeek(date) {
      let nowData = new Date(date); //传入时间参数,如 2021-11-09 获取给定日期所属的周 日期
      let currentDay = nowData.getDay();
      if (currentDay == 0) {
        currentDay = 7;
      }
      let beforweek = [],
        afterWeek = [];
      for (let i = 1; i <= 7; i++) {
        if (currentDay - i >= 0) {
          let DayTime =
            nowData.getTime() - (currentDay - i) * 24 * 60 * 60 * 1000;
          beforweek.push(new Date(DayTime).Format("yyyy-MM-dd"));
        } else {
          let DayTime = nowData.getTime() + (8 - i) * 24 * 60 * 60 * 1000;
          afterWeek.push(new Date(DayTime).Format("yyyy-MM-dd"));
        }
      }
      afterWeek = afterWeek.reverse();
      let dateList = [...beforweek, ...afterWeek];
      console.log(dateList);
      return dateList;
    },
    onShowDetailed() {
      // 判断是否是从首页或者审核历史查询详情跳转默认打开详情菜单
      if (this.$route.query.id) {
        this.$refs["detailedInformation"].periodId = Number(
          this.$route.query.id
        );
        this.$refs["detailedInformation"].form.updateTime =
          this.$route.query.dataPeriod.split("-");
        this.$refs["detailedInformation"].show();
      }
    },
  },
};
</script>
  <style scoped>
::v-deep.ivu-input-icon {
  height: 32px !important;
  line-height: 32px !important;
}
</style>
<style lang="less" scoped>
.content {
  height: 100%;
  &-bottom {
    background: #fff;
    border-radius: 6px;
    box-shadow: 1px 1px 2px 0px rgba(153, 182, 199, 0.2);
    padding: 20px;
  }
}

.formBox {
  width: 100%;
  background: #fff;
  border-radius: 6px;
  box-shadow: 1px 1px 2px 0px rgba(153, 182, 199, 0.2);
  padding: 20px 20px 1px;
  display: flex;
  flex-wrap: wrap;
  &-item {
    margin-right: 48px;
  }
}
.fw {
  display: flex;
  justify-content: space-between;
}
.fz {
  font-size: 20px;
  font-family: PingFang SC-Medium, PingFang SC;
  font-weight: 500;
  color: #333333;
  line-height: 23px;
}
::v-deep .ivu-table-wrapper-with-border {
  border-radius: 6px;
}
</style>
  